'use strict'
const { Blog, Op } = require('../model/index');

let fn_list = async function (ctx, next) {
    let keyword = ctx.request.query.keyword || '';
    if (keyword) {
        let list = await Blog.findAll(keyword).then({
            where: {
                [Op.or]: [{
                    id: isNaN(keyword) ? 0 : parseInt(keyword)
                }, {
                    title: keyword
                }, {
                    content: keyword
                }, {
                    classify: keyword
                }, {
                    author: keyword
                }, {
                    time: keyword
                }]
            },
            order: ['id']
        })
        ctx.body = {
            code: 1000,
            data: list,
            msg: "查询成功"
        }
    } else {
        let list = await Blog.findAll({
            where: {
                id: id
            },
            order: ['id']
        })
        ctx.body = {
            code: 1000,
            data: list,
            msg: "查询成功"
        }
    }
}

let fn_post = async function (ctx, next) {
    let obj = ctx.request.body;
    await Blog.create(obj);
    ctx.body = obj;
}

let fn_getbyid = async function (ctx, next) {
    let id = ctx.request.params.id;
    let list = await Blog.findByPk(id);
    if (list) {
        ctx.body = {
            code: 1000,
            data: list,
            msg: "查询成功"
        }
    } else {
        ctx.body = {
            code: 400,
            data: null,
            msg: "查询失败"
        }
    }
}

let fn_delete = async function (ctx, next) {
    let id = ctx.request.params.id;
    let list = await Blog.findByPk(id);
    if (list) {
        Blog.destroy({
            where: {
                id: id
            }
        })
        ctx.body = {
            code: 1000,
            data: { id },
            msg: "删除成功"
        }
    } else {
        ctx.body = {
            code: 400,
            data: null,
            msg: "删除失败"
        }
    }
}
let fn_put = async function (ctx, next) {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    let list = await Blog.findByPk(id);
    if (list) {
        Blog.update({
            where: {
                id: id
            }
        })
        ctx.body = {
            code: 1000,
            data: list,
            msg: "修改成功"
        }
    } else {
        ctx.body = {
            code: 400,
            data: null,
            msg: "修改失败"
        }
    }
}

module.exports = {
    'get /product': fn_list,
    'get /product/:id': fn_getbyid,
    'post /product': fn_post,
    'put /product.:id': fn_put,
    'delete /product/:id': fn_delete
}